package action;

import beans.UserBean;
import db.User;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;

/**
 * Delete user.
 * @author Tomas CASTA
 */
@UrlBinding("/userDelete.action")
public class DeleteUserActionBean implements ActionBean {
    /** action context */
    private ActionBeanContext context;
    /** user */
    private User user;

    public ActionBeanContext getContext() {
        return context;
    }

    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    /**
     * Delete user.
     * @return Resolution
     */
    @DefaultHandler
    public Resolution delete() {
        /* User is logged */
        if (null != context.getRequest().getSession().getAttribute("user")) {

            /* Get user info from session */
            UserBean userBean = (UserBean) context.getRequest().getSession().getAttribute("user");
            
            /* User is admin */
            if (userBean.getAdmin() == 1) {
                user = new User();
                user.setDb(this.context.getServletContext());

                /* Parse id from URI */
                try {
                    int id = Integer.valueOf(context.getRequest().getParameter("id"));                   

                    // User cannot delete himself
                    if (id != userBean.getId()) {

                        /* Delete user */
                        user.deleteUser(id);
                        return new ForwardResolution("/users.action");
                    }
                } catch (NumberFormatException e) {
                    Logger.getLogger(DeleteMessageActionBean.class.getName()).log(Level.SEVERE, null, e);
                    return new ForwardResolution("/users.action");
                }
            }
        }
        /* Some error, show index */
        return new ForwardResolution("/index.action");
    }
}
